<template>
  <div v-if="friendsData?.size" class="friManageFris">
    <ul class="friManageFris-header clearfix">
      <li
        v-for="{ id, title, className } in friManageFrisTits"
        :key="id"
        :class="className"
        class="friManageFris-item"
      >
        <div
          :class="{
            flex: true,
            'friend-check': true,
            isChecked: seleIds.size === friendsData.size,
            noChecked: seleIds.size !== friendsData.size,
          }"
          v-if="id === 1"
          @click="selectAll"
        >
          <SvgIcon popper-class="icon-checked" icon-class="check" />
        </div>
        {{ title }}
      </li>
    </ul>
    <el-scrollbar :max-height="contentHei" @scroll="scroll">
      <ul>
        <li
          v-for="[
            key,
            { avatar, nickName, remark, group, disabledOtherLook, disabledSelfLook },
          ] in friendsData"
          :key="key"
          class="friManageFris-li clearfix"
        >
          <div class="friManageFris-item friManageFris-select">
            <div
              :class="{
                flex: true,
                'friend-check': true,
                isChecked: seleIds.has(key),
                noChecked: !seleIds.has(key),
              }"
              @click="selectPart(key)"
            >
              <SvgIcon popper-class="icon-checked" icon-class="check" />
            </div>
          </div>
          <div class="friManageFris-item" style="width: 30%">
            <img
              class="friManageFris-item__img"
              :src="avatar"
              @click="openInfoCard(key, $event)"
              alt=""
            />
            <span
              class="friManageFris-item__name"
              :title="nickName"
              @click="sendMessage(key)"
              >{{ nickName }}</span
            >
          </div>
          <div class="friManageFris-item friManageFris-remark">
            <span
              class="friManageFris-item__remark"
              :title="remark"
              @click="modifyRemarkOrGroup(0, { remark, group, key })"
              >{{ remark }}</span
            >
          </div>
          <div class="friManageFris-item friManageFris-groups">
            <span
              class="friManageFris-item__group"
              :title="group"
              @click="modifyRemarkOrGroup(1, { remark, group, key })"
              >{{ group ? group : "无分组" }}</span
            >
          </div>
          <div
            class="friManageFris-item friManageFris-permission"
            @click="modifyPermission({ key, disabledOtherLook, disabledSelfLook, group })"
          >
            <span
              v-if="disabledOtherLook"
              class="momentsPermission-icons"
              title="不让对方看"
            >
              <SvgIcon popper-class="moments-icon" icon-class="moments" />
              <SvgIcon popper-class="moments-icon__locked" icon-class="lockClose" />
            </span>
            <span
              v-if="disabledSelfLook"
              class="momentsPermission-icons"
              title="不看对方"
            >
              <SvgIcon popper-class="moments-icon" icon-class="moments" />
              <SvgIcon popper-class="moments-icon__locked" icon-class="eyeOff" />
            </span>
            <span class="modifyPermWord" v-if="!disabledOtherLook && !disabledSelfLook"
              >修改权限</span
            >
          </div>
        </li>
      </ul></el-scrollbar
    >
    <usr-info-card
      ref="userInfoRef"
      v-model="showInfo"
      :user-id="currentId"
      to="#commManageRight"
      @update-position="updatePosition"
    ></usr-info-card>
    <setup
      to=".chat-box"
      v-model="showSetup"
      :type="setupState"
      v-model:info-rem-group="infoRemGroup"
      v-model:info-permission="infoPermission"
      :other-id="selectOtherId"
      :show-remark="showRemark"
      :show-group="showGroup"
      width="32%"
    ></setup>
    <opear-menu
      :modelValue="seleIds.size ? true : false"
      :ids="seleIds"
      :show-move-icon="showMoveIcon"
      :show-group-icon="showGroupIcon"
      :group="infoRemGroup.group"
      :info-permission="infoPermission"
    ></opear-menu>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, watch, onMounted, onBeforeUnmount, nextTick } from "vue";
import friManageFrisTits from "@/staticDatas/friManageFrisTits";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { useMessagePinia } from "@/pinia/messages";
import { useUserPinia } from "@/pinia/user";
import { storeToRefs } from "pinia";
import setup from "@/components/messages/colRight/detailMessage/setup.vue";
import usrInfoCard from "@/components/messages/colRight/detailMessage/usrInfoCard.vue";
import Trigger from "@/plugins/rigClickOpMen";
import opearMenu from "./opearMenu.vue";

const props = defineProps<{
  title: "all" | "disabledOtherLook" | "disabledSelfLook" | "groups";
  type?: string;
  friendsData?: Map<
    string,
    Pick<
      OtherIdInfo,
      | "avatar"
      | "nickName"
      | "remark"
      | "disabledOtherLook"
      | "disabledSelfLook"
      | "group"
    >
  >;
}>();

const router = useRouter();
const messageStore = useMessagePinia();
const { user } = storeToRefs(useUserPinia());

/**
 * 对方的备注和分组
 */
const infoRemGroup = ref<{ remark: string; group: string }>({
  remark: "",
  group: "",
});
/**
 * 对对方的朋友圈权限
 */
const infoPermission = ref<Permission>({
  disabledOtherLook: false,
  disabledSelfLook: false,
});

/**
 * 当前用户所勾选的好友的账号集合
 */
const seleIds = reactive<Set<string>>(new Set());
/**
 * 滚动条显示的最大高度
 */
const contentHei = ref<number>(440);
/**
 * 当用户勾选用户时是否显示移出分组按钮
 */
const showGroupIcon = ref<boolean>(false);

watch(
  () => seleIds.size,
  (size: number) => {
    if (size) {
      contentHei.value = 370;
      if (size === 1) {
        const data = props.friendsData?.get([...seleIds.values()][0])!;
        infoPermission.value.disabledOtherLook = data.disabledOtherLook;
        infoPermission.value.disabledSelfLook = data.disabledSelfLook;
        infoRemGroup.value.group = data.group;
        infoRemGroup.value.remark = data.remark;
        showGroupIcon.value = true;
      } else {
        try {
          seleIds.forEach((id) => {
            if (props.friendsData?.get(id)?.group) throw "";
          });
          showGroupIcon.value = true;
        } catch {
          showGroupIcon.value = false;
        }
      }
    } else setTimeout(() => (contentHei.value = 440), 250);
  }
);

// 勾选当前全部好友
const selectAll = () => {
  if (seleIds.size === props.friendsData?.size) seleIds.clear();
  else {
    for (const key of props.friendsData!.keys()) seleIds.add(key);
    if (props.title === "groups")
      infoRemGroup.value.group = props.type
        ? props.type === "无分组"
          ? ""
          : props.type
        : "";
  }
};

// 勾选部分好友
const selectPart = (key: string) => {
  if (seleIds.has(key)) seleIds.delete(key);
  else seleIds.add(key);
};

/**
 * 当用户勾选用户时是否显示移出分组按钮
 */
const showMoveIcon = ref<boolean>(false);
watch(
  () => props.type,
  (newType) => {
    if (newType) {
      seleIds.size && seleIds.clear();
      if (newType !== "无分组") showMoveIcon.value = true;
      else showMoveIcon.value = false;
    } else showMoveIcon.value = false;
  }
);

watch(
  () => props.title,
  (newTitle) => {
    if (newTitle !== "groups" && seleIds.size) seleIds.clear();
  }
);

/**
 * 是否正在给好友发送消息
 */
const isSendLoading = ref<boolean>(false);
// 开始给好友发送消息
const sendMessage = (userId: string) => {
  if (seleIds.has(userId) || isSendLoading.value) return;
  if (messageStore.chatList.has(userId))
    router.replace({ path: "/chatRecord", query: { userId } });
  else {
    isSendLoading.value = true;
    messageStore
      .readySendMessage({
        selfId: user.value.userId,
        otherId: userId,
      })
      .then((code: number) => {
        isSendLoading.value = false;
        if (code === 1) router.replace({ path: "/chatRecord", query: { userId } });
        else if (code === -2)
          ElMessage({
            type: "error",
            message: "操作失败，对方和自己不是好友关系",
            duration: 1500,
          });
        else
          ElMessage({
            type: "error",
            message: "跳转失败",
            duration: 1500,
          });
      })
      .catch(() => {
        isSendLoading.value = false;
        ElMessage({
          type: "error",
          message: "跳转失败",
          duration: 1500,
        });
      });
  }
};

/**
 * 当前选择操作的用户账号
 */
const selectOtherId = ref<string>("");
/**
 * 是否打开设置菜单
 */
const showSetup = ref<boolean>(false);
/**
 * 设置的状态，0代表设置备注和标签，1代表设置朋友圈权限
 */
const setupState = ref<0 | 1>(0);
/**
 * 是否是修改备注
 */
const showRemark = ref<boolean>(false);
/**
 * 是否是修改分组
 */
const showGroup = ref<boolean>(false);

// 修改备注或者分组
const modifyRemarkOrGroup = (
  type: 0 | 1,
  payload: { remark: string; group: string; key: string }
) => {
  if (seleIds.has(payload.key)) return;
  infoRemGroup.value.group = payload.group;
  infoRemGroup.value.remark = payload.remark;
  selectOtherId.value = payload.key;
  setupState.value = 0;
  if (type === 0) {
    showRemark.value = true;
    showGroup.value = false;
  } else {
    showRemark.value = false;
    showGroup.value = true;
  }
  showSetup.value = true;
};
// 修改朋友权限
const modifyPermission = (payload: {
  key: string;
  group: string;
  disabledOtherLook: boolean;
  disabledSelfLook: boolean;
}) => {
  if (seleIds.has(payload.key)) return;
  selectOtherId.value = payload.key;
  infoRemGroup.value.group = payload.group;
  infoPermission.value.disabledOtherLook = payload.disabledOtherLook;
  infoPermission.value.disabledSelfLook = payload.disabledSelfLook;
  setupState.value = 1;
  showSetup.value = true;
};

/* 打开资料卡片逻辑 */

const triggerUserInfo = ref<Trigger>();
/**
 * 是否需要打开用户信息卡片
 */
const showInfo = ref<boolean>(false);
/**
 * 给资料卡片组件一个ref属性，便于通过$refs访问
 */
const userInfoRef = ref<typeof usrInfoCard>();

// 滚动消息详情的滚动条触发的动作
const scroll = () => {
  if (showInfo.value) showInfo.value = false;
};

watch(
  () => showInfo.value,
  (newValue: boolean) => {
    if (newValue) triggerUserInfo.value?.resize();
    else triggerUserInfo.value?.removeResize();
  }
);

/**
 * 当前查看好友信息资料的userId值
 */
const currentId = ref<string>("");
/**
 * 当前用户点击事件
 */
const currentEv = ref<any>();
// 更新卡片的位置
const updatePosition = () =>
  triggerUserInfo.value?.computedDirection(
    userInfoRef.value?.$refs.userInfoRef as HTMLElement,
    currentEv.value
  );
// 打开资料卡片
const openInfoCard = (key: string, $event: MouseEvent) => {
  if (seleIds.has(key)) return;
  currentId.value = key;
  if (!showInfo.value) showInfo.value = true;
  currentEv.value = $event;
  nextTick(() => updatePosition());
};

const updateEle = () => {
  const ele: HTMLElement = document.getElementById("commManageRight") as HTMLElement;
  triggerUserInfo.value = new Trigger(ele);
};

onMounted(() =>
  setTimeout(() => {
    updateEle();
    globalThis.addEventListener("resize", updateEle);
    if (props.title === "groups" && props.type !== "无分组") showMoveIcon.value = true;
  })
);

onBeforeUnmount(() => globalThis.removeEventListener("resize", updateEle));
</script>

<style lang="scss" scoped>
.friManageFris {
  font-size: 13px;
  margin-left: 1px;

  &-li {
    transition: background-color 0.75s;

    &:hover {
      background-color: #f5f7fa;
    }
  }

  &-item {
    display: flex;
    align-items: center;
    float: left;
    height: 70px;

    &__img {
      @include setWidHei(40px, 40px);
      object-fit: cover;
      margin-right: 10%;
      cursor: pointer;
    }

    @mixin name($width) {
      display: inline-block;
      max-width: $width;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }

    &__name {
      @include name(calc(100% - 40px - 15%));
      cursor: pointer;
    }

    &__remark,
    &__group {
      cursor: pointer;
      @include name(85%);
    }

    .momentsPermission-icons {
      position: relative;
      margin-right: 5%;
      color: rgba(0, 0, 0, 0.432);

      .moments-icon {
        font-size: 22px;
        opacity: 0.6;

        &__locked {
          font-size: 15px;
          position: absolute;
          opacity: 0.9;
          right: 0;
          bottom: 0;
        }
      }
    }
  }

  &-header {
    background-color: rgb(244, 248, 255);

    & > li {
      height: 60px;
    }
  }

  &-select {
    width: 16%;
  }

  &-name {
    width: 30%;
    justify-content: center;
  }

  &-permission {
    cursor: pointer;

    &__title {
      cursor: text;
    }

    .modifyPermWord {
      display: none;
    }

    &:hover {
      .modifyPermWord {
        display: block;
      }
    }
  }

  &-remark,
  &-groups,
  &-permission {
    width: 18%;
    justify-content: center;
  }

  .friend-check {
    @include setWidHei(15px, 15px);
    margin-right: 10%;
    margin-left: 16%;
    transition: background-color 0.25s;
  }
}
</style>
